package com.eastfair.home.service.impl;

import cn.hutool.core.bean.BeanUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.home.dao.SupervisionItemManagementMapper;
import com.eastfair.home.dto.SupervisionItemManagementDTO;
import com.eastfair.home.dto.SupervisionItemManagementQuery;
import com.eastfair.home.dto.SupervisionItemQuestionQuery;
import com.eastfair.home.entity.SupervisionItemManagement;
import com.eastfair.home.enumeration.SupervisionItemManagementSupervisionItemEnum;
import com.eastfair.home.service.SupervisionItemManagementService;
import com.eastfair.home.service.SupervisionItemQuestionService;
import com.eastfair.home.vo.SupervisionItemManagementVO;
import com.eastfair.home.vo.SupervisionItemQuestionVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 业务实现类
 * 监督项管理
 * </p>
 *
 * @author linan
 * @date 2022-11-29
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class SupervisionItemManagementServiceImpl extends SuperServiceImpl<SupervisionItemManagementMapper, SupervisionItemManagement> implements SupervisionItemManagementService {


    /**
     * 监督项管理问卷
     */
    @Resource
    private SupervisionItemQuestionService supervisionItemQuestionService;

    public static final int SORT_ONE = 1;
    public static final int SORT_TWO = 2;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<SupervisionItemManagement> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }



    @Override
    protected R<Boolean> handlerSave(SupervisionItemManagement model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<SupervisionItemManagement> list(SupervisionItemManagementDTO modelDTO, List<Long> ids) {
        return ((SupervisionItemManagementService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'updatedName', #args[0]?.updatedName}," +
                            "{'exhibitionManageId', #args[0]?.exhibitionManageId}," +
                            "{'builderId', #args[0]?.builderId}," +
                            "{'builderName', #args[0]?.builderName}," +
                            "{'homeCourtId', #args[0]?.homeCourtId}," +
                            "{'homeCourtName', #args[0]?.homeCourtName}," +
                            "{'sort', #args[0]?.sort}," +
                            "{'supervisionItem', #args[0]?.supervisionItem}," +
                            "{'supervisionItemName', #args[0]?.supervisionItemName}," +
                            "{'questionNum', #args[0]?.questionNum}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<SupervisionItemManagement> listOfCache(SupervisionItemManagementDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<SupervisionItemManagement> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getUpdatedName()), SupervisionItemManagement::getUpdatedName, modelDTO.getUpdatedName());
            queryWrapper.lambda().eq(modelDTO.getExhibitionManageId() != null, SupervisionItemManagement::getExhibitionManageId, modelDTO.getExhibitionManageId());
            queryWrapper.lambda().eq(modelDTO.getBuilderId() != null, SupervisionItemManagement::getBuilderId, modelDTO.getBuilderId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBuilderName()), SupervisionItemManagement::getBuilderName, modelDTO.getBuilderName());
            queryWrapper.lambda().eq(modelDTO.getHomeCourtId() != null, SupervisionItemManagement::getHomeCourtId, modelDTO.getHomeCourtId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getHomeCourtName()), SupervisionItemManagement::getHomeCourtName, modelDTO.getHomeCourtName());
            queryWrapper.lambda().eq(modelDTO.getSort() != null, SupervisionItemManagement::getSort, modelDTO.getSort());
            queryWrapper.lambda().eq(Objects.nonNull(modelDTO.getSupervisionItem()), SupervisionItemManagement::getSupervisionItem, modelDTO.getSupervisionItem());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSupervisionItemName()), SupervisionItemManagement::getSupervisionItemName, modelDTO.getSupervisionItemName());
            queryWrapper.lambda().eq(modelDTO.getQuestionNum() != null, SupervisionItemManagement::getQuestionNum, modelDTO.getQuestionNum());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(SupervisionItemManagement::getId, ids);
        }
        queryWrapper.lambda().eq(SupervisionItemManagement::getIsDeleted, BusinessConstant.DELETE_NO);
        List<SupervisionItemManagement> modelList = list(queryWrapper);
        return modelList;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Boolean saveSupervisionItemManagement(SupervisionItemManagementDTO dto) {
        // 查询原展会主场关系是否与现在一致
        SupervisionItemManagement one = getOne(new QueryWrapper<SupervisionItemManagement>().lambda()
                .eq(SupervisionItemManagement::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(SupervisionItemManagement::getExhibitionManageId, dto.getExhibitionManageId())
                .eq(SupervisionItemManagement::getSort, SORT_ONE));
        if(Objects.nonNull(one) && one.getHomeCourtId().equals(dto.getHomeCourtId())){
            return true;
        }
        // 作废原展会数据
        update(new UpdateWrapper<SupervisionItemManagement>()
                .lambda().eq(SupervisionItemManagement::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(SupervisionItemManagement::getExhibitionManageId, dto.getExhibitionManageId())
                .set(SupervisionItemManagement::getIsDeleted, BusinessConstant.DELETE_YES));
        // 插入新的记录
        SupervisionItemManagement arrangement = BeanUtil.copyProperties(dto, SupervisionItemManagement.class);
        arrangement.setSort(SORT_ONE);
        arrangement.setIsEnabled(BusinessConstant.NO);
        arrangement.setUpdatedBy(null);
        arrangement.setUpdateTime(null);
        arrangement.setSupervisionItem(SupervisionItemManagementSupervisionItemEnum.ARRANGEMENT);
        arrangement.setSupervisionItemName(SupervisionItemManagementSupervisionItemEnum.ARRANGEMENT.getDesc());
        save(arrangement);
        SupervisionItemManagement dismantling = BeanUtil.copyProperties(dto, SupervisionItemManagement.class);
        dismantling.setSort(SORT_TWO);
        dismantling.setIsEnabled(BusinessConstant.NO);
        dismantling.setUpdatedBy(null);
        dismantling.setUpdateTime(null);
        dismantling.setSupervisionItem(SupervisionItemManagementSupervisionItemEnum.DISMANTLING);
        dismantling.setSupervisionItemName(SupervisionItemManagementSupervisionItemEnum.DISMANTLING.getDesc());
        save(dismantling);
        return true;
    }

    @Override
    public List<SupervisionItemManagementVO> getSupervisionItemManagement(SupervisionItemManagementQuery query) {
        List<SupervisionItemManagement> list = list(new QueryWrapper<SupervisionItemManagement>().lambda()
                .eq(SupervisionItemManagement::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(SupervisionItemManagement::getExhibitionManageId, query.getExhibitionManageId())
                .eq(SupervisionItemManagement::getHomeCourtId, query.getHomeCourtId())
                .eq(Objects.nonNull(query.getIsEnabled()),SupervisionItemManagement::getIsEnabled, query.getIsEnabled())
                .eq(Objects.nonNull(query.getSupervisionItem()), SupervisionItemManagement::getSupervisionItem, query.getSupervisionItem())
                .like(StringUtils.isNotBlank(query.getKeyword()), SupervisionItemManagement::getSupervisionItemName, query.getKeyword())
                .like(StringUtils.isNotBlank(query.getKeyword()), SupervisionItemManagement::getUpdatedName, query.getKeyword())
                .orderByAsc(SupervisionItemManagement::getSort));
        return doToVos(list);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Boolean updateSupervisionItemManagement(SupervisionItemManagementDTO dto) {
        SupervisionItemManagement supervisionItemManagement = BeanUtil.copyProperties(dto, SupervisionItemManagement.class);
        return updateById(supervisionItemManagement);
    }

    @Override
    public List<SupervisionItemQuestionVO> queryQuestion(SupervisionItemManagementQuery query) {
        List<SupervisionItemManagementVO> supervisionItemManagement = getSupervisionItemManagement(query);
        if(CollectionUtils.isEmpty(supervisionItemManagement)){
            return Collections.emptyList();
        }else {
            SupervisionItemManagementVO supervisionItemManagementVO = supervisionItemManagement.get(0);
            Long id = supervisionItemManagementVO.getId();
            return supervisionItemQuestionService.querySupervisionItemQuestion(SupervisionItemQuestionQuery.builder().supervisionItemManagementId(id).build());
        }
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public SupervisionItemManagementVO doToVo(SupervisionItemManagement model) {
        SupervisionItemManagementVO modelVo = new SupervisionItemManagementVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<SupervisionItemManagementVO> doToVos(List<SupervisionItemManagement> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<SupervisionItemManagementVO> result = new ArrayList<>();
        for (SupervisionItemManagement model : modelList) {
            String updatedName = model.getUpdatedName();
            if(StringUtils.isBlank(updatedName)){
                model.setUpdateTime(null);
            }
            result.add(doToVo(model));
        }
        return result;
    }
}
